package com.asia5b.a5mall.order.widget

import android.content.Context
import android.graphics.Color
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import com.asia5b.a5mall.middleware.utils.DisplayUtils
import com.asia5b.a5mall.middleware.widget.GridSpacingItemDecoration
import com.asia5b.a5mall.middleware.widget.popup.PopupItemTextInterface
import com.asia5b.a5mall.order.R
import com.asia5b.a5mall.order.adapter.SelectAdapter

/**
 * Created by zhangyuncai on 2020/3/20.
 */
class OrderTypeSelectView @JvmOverloads constructor(
        context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {

    companion object {
        fun addView(parentView: FrameLayout): OrderTypeSelectView {
            val childView = OrderTypeSelectView(parentView.context)
            val layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)
            parentView.addView(childView, layoutParams)
            return childView
        }
    }

    val mDatas = arrayListOf<PopupItemTextInterface>()
    val mAdapter = SelectAdapter(mDatas)
    var callback: ((Int)->Unit)? = null

    var mRecyclerView: RecyclerView
    var tv_ordertype_title:TextView

    var selectPostion = -1
        set(value) {
            field = value
            mAdapter.notifyDataSetChanged()
        }

    init {
        View.inflate(context!!, R.layout.view_ordertype_select, this)
        mRecyclerView = findViewById<RecyclerView>(R.id.rv_orderlist_typelist)
        tv_ordertype_title = findViewById<TextView>(R.id.tv_ordertype_title)
        mRecyclerView.run {
            layoutManager = GridLayoutManager(context!!, 3)
            adapter = mAdapter
            addItemDecoration(GridSpacingItemDecoration(3, DisplayUtils.dip2px(context!!, 10f), false))
        }
        mAdapter.setOnItemClickListener { adapter, view, position ->
            selectPostion = position
            callback?.invoke(position)
            dismiss()
        }
        setBackgroundColor(Color.parseColor("#77000000"))
        setOnClickListener {
            dismiss()
        }
    }

    fun <T : PopupItemTextInterface> setDatas(datas: ArrayList<T>) {
        mDatas.clear()
        mDatas.addAll(datas)
        mAdapter.notifyDataSetChanged()
    }

    fun isShowing(): Boolean {
        return visibility == View.VISIBLE
    }

    fun show() {
        visibility = View.VISIBLE
    }

    fun dismiss() {
        visibility = View.GONE
    }

    fun setTitle(title: String) {
        tv_ordertype_title.text=title
    }

}